<template>
  <el-card>
    <template #header>
      <div
        class="card-header d-flex justify-content-between align-items-center"
      >
        <div>
          <el-icon><Bell /></el-icon>
          <span>最新异常日志</span>
        </div>
      </div>
    </template>

    <div class="filter-container">
      <el-input v-model="filterText" placeholder="输入关键字进行筛选" clearable>
        <template #prefix>
          <el-icon><Filter /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="filteredData" style="width: 100%" stripe>
      <el-table-column prop="time" label="时间" width="120" />
      <el-table-column prop="level" label="级别" width="100">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.level)" size="small">
            {{ row.level }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="120" />
      <el-table-column prop="sourceIp" label="源IP" width="150" />
      <el-table-column prop="message" label="关键信息" />
    </el-table>

    <div
      class="d-flex justify-content-between align-items-center px-3 py-2 border-top"
    >
      <div class="small text-muted">显示 {{ filteredData.length }} 条</div>
      <el-button
        type="primary"
        :disabled="apiStore.apiStates.latestErrors.loading"
        @click="loadMore"
      >
        <el-icon><Plus /></el-icon>
        加载更多
      </el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { Bell, Filter, Plus } from '@element-plus/icons-vue'
import { ref, watch, computed } from 'vue'
import useApiStore from '@/core/apiStore'

const apiStore = useApiStore()
const tableData = ref<LogItem[]>([])
const nextStartId = ref<number | null>(null)
const filterText = ref<string>('')

interface LogItem {
  time: string
  level: string
  type: string
  sourceIp: string
  message: string
}

const transformLogs = (logs: any[]): LogItem[] => {
  return logs.map(log => ({
    time: log.date,
    level: log.log_level,
    type: log.log_type,
    sourceIp: log.src_ip,
    message: log.message,
  }))
}

const getTagType = (level: string) => {
  return level === 'ERROR' ? 'danger' : level === 'WARN' ? 'warning' : ''
}

const fetchLogs = async (startId?: number) => {
  if (apiStore.apiStates.latestErrors.loading) return {}
  try {
    const { data: result } = await apiStore.latestErrors({ startId })
    return result
  } catch (error) {
    console.error('Failed to fetch logs:', error)
    throw error
  }
}

const isLoadingMore = ref(false)
const loadMore = async () => {
  if (nextStartId.value !== null) {
    isLoadingMore.value = true
    const { logs, next_start_id } = await fetchLogs(nextStartId.value)
    tableData.value = [...tableData.value, ...logs]
    nextStartId.value = next_start_id
    isLoadingMore.value = false
  }
}

const filteredData = computed(() => {
  if (!filterText.value) return tableData.value
  const lowerCaseFilter = filterText.value.toLowerCase()
  return tableData.value.filter(
    item =>
      item.level.toLowerCase().includes(lowerCaseFilter) ||
      item.type.toLowerCase().includes(lowerCaseFilter) ||
      item.sourceIp.toLowerCase().includes(lowerCaseFilter) ||
      item.message.toLowerCase().includes(lowerCaseFilter)
  )
})

watch(
  apiStore.apiStates.latestErrors,
  newVal => {
    const data = newVal.data?.data
    const { logs, next_start_id } = data || {}
    if (logs && !isLoadingMore.value) {
      const newLogs = transformLogs(logs)
      tableData.value = [...tableData.value, ...newLogs]
      nextStartId.value = next_start_id
    }
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.d-flex {
  display: flex;
}

.justify-content-between {
  justify-content: space-between;
}

.align-items-center {
  align-items: center;
}

.px-3 {
  padding-left: 1rem;
  padding-right: 1rem;
}

.py-2 {
  padding-top: 0.5rem;
  padding-bottom: 0.5rem;
}

.border-top {
  border-top: 1px solid #ebeef5;
}

.small {
  font-size: 0.875rem;
}

.text-muted {
  color: var(--gray-color);
}

:deep(.el-card__header) {
  padding: 1rem 1.25rem;
}

:deep(.el-table) {
  margin-bottom: 0;

  th {
    background: var(--light-bg);
    font-weight: 600;
    color: #475569;
    border-bottom: 2px solid #e9ecef;
    padding: 0.75rem 1rem;
    font-size: 0.9rem;
  }

  td {
    padding: 0.75rem 1rem;
    vertical-align: middle;
    border-color: rgba(0, 0, 0, 0.05);
    font-size: 0.9rem;
  }

  &.el-table--striped .el-table__body tr.el-table__row--striped td {
    background-color: #fafafa;
  }

  tr:hover {
    background-color: rgba(67, 97, 238, 0.05) !important;
  }
}

.filter-container {
  margin-bottom: 1rem;
}
</style>
